import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row, Col, Card, Form, Input, Select, Icon,
  Button, Table, List, message, Checkbox
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';
import styles from './OrganizationEdit.less';
import querystring from 'querystring';
/*
 角色管理权限配置界面
*/

const { Option, OptGroup } = Select;


@connect(({ role }) => ({
  role,
}))
export default class JurisdictionConfiguration extends PureComponent {
  state = {
    id: '',
    selectedRowId: [],
    selectedRowKeys: [],
    ItemId: {},
    resourcesListId: {},
    selectedResourceKeys: [],
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    // console.log(`this.props.location`);
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      id: params.id
    })
    dispatch({
      type: 'role/getAllMenusByRoleId',
      payload: {
        roleId: params.id
      },
      callback:()=>{
        const { role: { resourcesList } } = this.props;
        const { allResource, roleResource ,roleMenuIdList} = resourcesList;
        
        // console.log("resourcesList=", resourcesList);
        // console.log("roleResource=", roleResource);

        let selectedResourceKeys = [];
        roleResource.map((item)=>{
          selectedResourceKeys.push(item.id);
        });
        
        this.setState({
          resourcesListId: resourcesList,
          selectedResourceKeys,
          selectedRowId: roleMenuIdList,
        });
        // console.log("selectedRowId=", this.state.selectedRowId);
      }
    });
  }

  addSelection = (key) => {
    const selectedRowKeys = [...this.state.selectedRowKeys];

    if (selectedRowKeys.indexOf(key) == -1) {
      selectedRowKeys.push(key);
    }
    this.setState({
      selectedRowKeys,
    });
  }

  addResourceSelection = (key) => {
   
    const selectedResourceKeys = [...this.state.selectedResourceKeys];

    if (selectedResourceKeys.indexOf(key) == -1) {
      selectedResourceKeys.push(key);
    }
    this.setState({
      selectedResourceKeys,
    });
  }

  handleUpdateAllRoleId = () => {   
    const { dispatch } = this.props;
    let hash = [];
    let arr = [];
    const selectedRowId = [...this.state.selectedRowId]
    for (let i = 0; i < selectedRowId.length; i++) {
      hash[selectedRowId[i]] != null;
      if (!hash[selectedRowId[i]]) {
        arr.push(selectedRowId[i]);
        hash[selectedRowId[i]] = true;
      }
    }
    // console.log("arrAQQAAQQAAQQAAQAQAQA",arr)
    dispatch({
      type: 'role/updateAllMenusByRoleId',
      payload: {
        id: this.state.id,
        menuIdList: arr,
        resourceIdList: this.state.selectedResourceKeys
      },
    });
  }

  columns = [{
    title: '功能',
    dataIndex: 'name',
    key: 'name',
    width: '20%'
  }, {
    title: '权限',
    key: 'id',
    dataIndex: 'id',
    render: (text, item) => {
      return (
        <div>
          {
            item.resourceList.map((resource) => {
              const defaultChecked = this.state.selectedResourceKeys.indexOf(resource.id) > -1;
             
              return (
                <Checkbox
                  key={resource.id}
                  checked={defaultChecked}
                  onChange={(e) => {
                    
                    const selectedResourceKeys = [...this.state.selectedResourceKeys];
                    const selectedRowId = [...this.state.selectedRowId];
                    // const indexId = selectedRowId.indexOf(item.id);
                    const index = selectedResourceKeys.indexOf(resource.id);
                    
                    if(e.target.checked){
                      if ( index == -1) {   
                        selectedRowId.push(item.id);         
                        selectedResourceKeys.push(resource.id);
                        console.log("selectedResourceKeys=",this.state.selectedRowId);
                      }
                      
                    }else{
                      if ( index != -1) {
                        // selectedRowId.splice(indexId,1);
                        selectedResourceKeys.splice(index,1);
                      }
                    }   
                    
                    this.setState({
                      selectedRowId,
                      selectedResourceKeys,
                    });
                    console.log("selectedRowId2131313131313",selectedRowId)
                    console.log("selectedRowId",selectedRowId)
                    // message.success("您点击了权限");
                    
                    // //this.addResourceSelection(resource.id);

                    // const selectedResourceKeys = [...this.state.selectedResourceKeys];
                    // //错误示例:
                    // //const selectedResourceKeys = this.state.selectedResourceKeys;

                    // if (selectedResourceKeys.indexOf(resource.id) == -1) {
                    //   selectedResourceKeys.push(resource.id);
                    // }
                   


                    // let isAllResourceInThisMenuSelected = true;
                    // item.resourceList.map((resourceInstance)=>{
                    //   if(selectedResourceKeys.indexOf(resourceInstance.id)==-1){
                    //     isAllResourceInThisMenuSelected = false;
                    //     console.log("isAllResourceInThisMenuSelected=false resourceInstance=",resourceInstance);
                    //     console.log("this.state.selectedResourceKeys=",this.state.selectedResourceKeys);
                    //   }
                    // });

                    // if(isAllResourceInThisMenuSelected){
                    //   this.addSelection(item.id);
                    // }

                    //console.log("this.state.selectedRowKeys=", this.state.selectedRowKeys);

                  }}>{resource.name}</Checkbox>
              );
            })
          }

        </div>
      );
    }
  }];


  render() {
    const { role: { resourcesList } } = this.props;
    const { allResource } = resourcesList;
    const { selectedRowKeys } = this.state;

    return (
      <PageHeaderLayout title="权限配置">
        <Card
          bordered={false} >
          {/* {JSON.stringify(resourcesList)} */}
          <Table
            bordered={false}
            pagination={false}
            dataSource={allResource}
            columns={this.columns}
            rowKey="id"
            defaultExpandAllRows={true}
          >
          </Table>
          <div className={styles.tableListOperator}>
            <Button style={{ marginTop: 30 }} type="primary" onClick={() => this.handleUpdateAllRoleId()}>
              提交
            </Button>
          </div>
        </Card>

      </PageHeaderLayout>
    );
  }
}